import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Location } from '@angular/common';

import { TransactionService } from '../../../services/transaction.service';
import { aroAnimation } from '../../../animation';

@Component({
  selector: 'app-bookcase',
  templateUrl: './bookcase.component.html',
  styleUrls: ['./bookcase.component.css'],
  animations: [aroAnimation]
})
export class BookcaseComponent implements OnInit {

  public readerId: string = localStorage.getItem('ReaderId');

  public bookcase: Array<any> = [];
  // public tempBookcase: Array<any> = [];

  constructor(private location: Location, private currentRouter: ActivatedRoute, private router: Router,
    private transactionService: TransactionService
  ) { }

  ngOnInit() {
    if (this.readerId) {
      this.transactionService.getMyShelf(this.readerId).subscribe(res => {
        // console.log(res);
        this.bookcase = res.Data;
        localStorage.setItem('BookcaseSummary', JSON.stringify(this.bookcase.length));
      });
    }
  }

  public removeBook_onclick(item): void {
    this.transactionService.removeBookFromShelf(item.Book.Id, this.readerId).subscribe(res => {
      if (res.Data == 1) {
        this.bookcase = this.bookcase.filter(book => book.Book.Id != item.Book.Id);
      }
    });
  }

  public goLogin_onclick(): void {
    this.router.navigate(['./login']);
  }

  public goCategory(): void {
    this.router.navigate(['./content/category']);
  }

  public goBack_onclick(): void {
    this.location.back();
  }

  public clearBookcase_onclick() {
    if (this.bookcase) {
      this.transactionService.removeMyShelf(this.readerId).subscribe(res => {
        // console.log(res);
        this.bookcase = [];
      });
    }
  }

  public submitOrders_onclick() {
    if (this.bookcase) {
      this.transactionService.submitOrder(this.readerId).subscribe(res => {
        // console.log(res);
        this.bookcase = [];
      });
    }
  }

}
